<?php


namespace addon\hotel\model;


use app\model\BaseModel;
use app\model\hotel\Hotel;
use app\model\system\Config;
use app\model\system\Cron;
use Carbon\Carbon;

/**
 * 系统站账户
 */
class HotelAccount extends BaseModel
{
    public $from_type = [
        'order' => [
            'type_name' => '订单结算',
            'type_url' => '',
        ],
        'withdraw' => [
            'type_name' => '提现',
            'type_url' => '',
        ],
    ];
    /**************************************************************店铺账户****************************************************************/
    /**
     * 添加分站账户数据
     * @param int $hotel_id
     * @param int $account_type 账户类型 默认account
     * @param float $account_data
     * @param string $relate_url
     * @param string $remark
     */
    public function addAccount($hotel_id, $account_type = 'account', $account_data, $from_type, $relate_tag, $remark)
    {
        $data = array(
            'account_no' => date('YmdHi').rand(1000,9999),
            'hotel_id' => $hotel_id,
            'account_type' => $account_type,
            'account_data' => $account_data,
            'from_type' => $from_type,
            'type_name' => $this->from_type[$from_type]['type_name'],
            'relate_tag' => $relate_tag,
            'create_time' => time(),
            'remark' => $remark
        );

        $account = model('hotel')->getInfo([
            'hotel_id' => $hotel_id
        ], $account_type);
        $account_new_data = (float) $account[ $account_type ] + (float) $account_data;
        if ((float) $account_new_data < 0) {
            return $this->error('', 'RESULT_ERROR');
        }

        $res = model('hotel_account')->add($data);
        $res = model('hotel')->update([
            $account_type => $account_new_data
        ], [
            'hotel_id' => $hotel_id
        ]);
        //event("AddAccount", $data);
        return $this->success($res);
    }
    /**************************************************************账户查询****************************************************************/
    /**
     * 获取账户流水
     * @param unknown $condition
     * @param string $field
     * @param string $order
     * @param string $limit
     * @return multitype:number unknown
     */
    public function getAccountList($condition = [], $field = '*', $order = '', $limit = null)
    {
        $list = model('hotel_account')->getList($condition, $field, $order, '', '', '', $limit);
        return $this->success($list);
    }


    /**
     * 获取店铺账户流水分页
     * @param unknown $condition
     * @param number $page
     * @param string $page_size
     * @param string $order
     * @param string $field
     * @return multitype:number unknown
     */
    public function getAccountPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = '', $field = '*')
    {

        $list = model('hotel_account')->pageList($condition, $field, $order, $page, $page_size);
        return $this->success($list);
    }

    /**
     * 按照订单查询账户流水
     * @param unknown $condition
     * @param number $page
     * @param string $page_size
     * @param string $order
     * @param string $field
     */
    public function getOrderAccountPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = 'na.create_time desc')
    {
        $field = 'no.hotel_id, no.hotel_name, no.order_no, no.order_money, na.account_data, no.shop_money, na.create_time, na.remark';
        $alias = 'na';
        $join = [
            [
                'hotel_order no',
                'na.relate_tag = no.order_id',
                'left'
            ],
        ];
        $list = model("hotel_account")->pageList($condition, $field, $order, $page, $page_size, $alias, $join);
        return $this->success($list);
    }

    /**
     * 获取平台或者分站账户
     * @return multitype:number unknown
     */
    public function getAccountInfo($hotel_id = 0)
    {
        $info = model("hotel")->getInfo([['hotel_id', '=', $hotel_id]], "account");
        return $this->success($info);
    }


    /**
     * 获取店铺余额统计
     */
    public function getShopOrderAccountSum()
    {
        $money = model("hotel")->getSum([], 'account');
        return $this->success($money);
    }

    /**
     * 查询店铺提现总额
     * @return multitype:number unknown
     */
    public function getShopWithDrawSum()
    {
        $money = model("hotel")->getSum([], 'account_withdraw');
        return $this->success($money);
    }
    /**
     * 整体查询店铺总额信息
     */
    public function getShopDataSum()
    {
        $info = model("hotel")->getInfo([['hotel_id', '>', 0]], "sum(account) as account, sum(account_withdraw) as account_withdraw, sum(account_withdraw_apply) as account_withdraw_apply");
        return $this->success($info);
    }

    /**
     * 获取整体店铺结算
     */
    public function getShopSettlementSum()
    {
        $field = '
                sum(hotel_money) as hotel_money,
                sum(refund_hotel_money) as refund_hotel_money,
                sum(commission) as commission,
                sum(platform_money) as platform_money
                ';
        $res = model("hotel_settlement_period")->getInfo([['period_id', '>', 0]], $field);
        if($res['hotel_money'] == null){
            $res['hotel_money'] = '0.00';
        }
        if($res['refund_hotel_money'] == null){
            $res['refund_hotel_money'] = '0.00';
        }
        if($res['commission'] == null){
            $res['commission'] = '0.00';
        }
        if($res['platform_money'] == null){
            $res['platform_money'] = '0.00';
        }

        return $this->success($res);
    }

    /**
     * 获取订单金额
     */
    public function getOrderSum()
    {
        $money = model("hotel_order")->getSum([['order_status', '>', 0]], 'order_money');
        return $this->success($money);
    }

    /**
     * 会员金额账户
     * @return multitype:
     */
    public function getMemberBalanceSum()
    {
        $field = '
                sum(balance) as balance, 
                sum(balance_money) as balance_money,
                sum(balance_withdraw_apply) as balance_withdraw_apply, 
                sum(balance_withdraw) as balance_withdraw
                ';
        $info = model("member")->getInfo([['member_id', '>', 0]], $field);
        if($info['balance'] == null){
            $info['balance'] = '0.00';
        }
        if($info['balance_money'] == null){
            $info['balance_money'] = '0.00';
        }
        if($info['balance_withdraw_apply'] == null){
            $info['balance_withdraw_apply'] = '0.00';
        }
        if($info['balance_withdraw'] == null){
            $info['balance_withdraw'] = '0.00';
        }
        return $this->success($info);
    }


    /**************************************************************店铺提现转账*************************************************************/

    /**
     * 添加店铺转账
     * @param unknown $data
     */
    public function addShopWithdraw($data)
    {
        $res = model("hotel_withdraw")->add($data);
        if($res)
        {
            $this->addShopAccount($data['site_id'], 'account', $data['money']*(-1), 'withdraw', $res, "店铺提现，账单编号:".$data['withdraw_no']);
        }

        return $this->success($res);
    }

    /**
     * 编辑店铺转账
     * @param unknown $data
     * @param unknown $condition
     */
    public function editShopWithdraw($data, $condition)
    {
        $res = model('hotel_withdraw')->update($data, $condition);
        return $this->success($res);
    }

    /**
     * 获取提现申请流水号
     */
    public function getWithdrawNo()
    {
        return date('YmdHi').rand(1111,9999);
    }


    /**
     * 店铺申请转账
     * @param $site_id
     * @param $money
     * @return array
     */
    public function applyWithdraw($hotel_id, $money)
    {
        //查询店铺信息
        $shop = new Hotel();
        $shop_info = $shop->getHotelInfo([['hotel_id', '=', $hotel_id]], 'hotel_name,account,account_withdraw_apply,bank_number,id_card_name,telphone');

        if($shop_info['data']['bank_number'] == ''){
            return $this->error("", "请先添加开户行信息");
        }

        //开始记录申请
        if(bcsub($shop_info['data']['account'], $shop_info['data']['account_withdraw_apply'], 2) < $money)
        {
            return $this->error("", "SHOP_APPLY_MONEY_NOT_ENOUGH");
        }
        $withdraw_no = $this->getWithdrawNo();

        model("hotel_withdraw")->startTrans();
        try{
            $data = [
                'withdraw_no' => $withdraw_no,
                'hotel_id' => $hotel_id,
                'hotel_name' => $shop_info['data']['hotel_name'],
                'name' => $shop_info['data']['id_card_name'],
                'mobile' => $shop_info['data']['telphone'],
                'bank_type' => 1,
                //'settlement_bank_account_name' => $shop_info['data']['settlement_bank_account_name'],
                'settlement_bank_account_number' => $shop_info['data']['bank_number'],
                //'settlement_bank_name' => $shop_cert_info['data']['settlement_bank_name'],
                //'settlement_bank_address' => $shop_cert_info['data']['settlement_bank_address'],
                'money' => $money,
                'apply_time' => time(),
            ];
            model("hotel_withdraw")->add($data);
            model("hotel")->setInc([ [ 'hotel_id', '=', $hotel_id ] ], 'account_withdraw_apply',$money);
//            $res = $this->addShopWithdraw($data);
            model("hotel_withdraw")->commit();
            return $this->success();
        }catch(\Exception $e)
        {
            model("hotel_withdraw")->rollback();
            return $this->error('', $e->getMessage());
        }
    }

    /**
     * 审核通过
     * @param unknown $apply_ids
     */
    public function applyPass($apply_ids)
    {
        $res = model('hotel_withdraw')->update(['status' => 1], [['id', 'in', $apply_ids], ['status', '=', 0]]);
        return $this->success($res);
    }

    /**
     * 审核拒绝
     * @param unknown $apply_id
     */
    public function applyReject($apply_id)
    {
        $res = model('hotel_withdraw')->update(['status' => -1], [['id', '=', $apply_id], ['status', '=', 0]]);
        if($res)
        {
            $apply_info = model('hotel_withdraw')->getInfo([['id', '=', $apply_id]], 'hotel_id,money,withdraw_no');
            model('hotel')->setDec([ [ 'hotel_id', '=', $apply_info['hotel_id'] ] ], 'account_withdraw_apply',$apply_info['money']);
        }
        return $this->success($res);
    }
    /**
     * 转账数据
     * @param unknown $apply_ids
     */
    public function applyPay($apply_ids)
    {
        $res = model('hotel_withdraw')->update(['status' => 2, 'payment_time' => time()], [['id', 'in', $apply_ids], ['status', '=', 1]]);
        return $this->success($res);
    }

    /**
     * 商家转账
     * @param array $condition
     * @param $data
     */
    public function shopWithdrawPass($id,$data)
    {
        $data['status'] = 2;
        $data['payment_time'] = time();
        model('hotel_withdraw')->startTrans();

        try{

            model('hotel_withdraw')->update($data,[ ['id','=',$id] ]);

            $apply_info = model('hotel_withdraw')->getInfo([['id', '=', $id]], 'hotel_id,money,withdraw_no');

            //减少提现中金额
            model('hotel')->setDec([ [ 'hotel_id', '=', $apply_info['hotel_id'] ] ], 'account_withdraw_apply',$apply_info['money']);

            //增加已提现金额
            model('hotel')->setInc([ [ 'hotel_id', '=', $apply_info['hotel_id'] ] ], 'account_withdraw',$apply_info['money']);
            //增加流水
            $this->addAccount($apply_info['hotel_id'], 'account', $apply_info['money']*(-1), 'withdraw', $id, "店铺提现，提现账单编号:".$apply_info['withdraw_no']);
            model("hotel_withdraw")->commit();
            return $this->success();
        }catch(\Exception $e)
        {
            model("hotel_withdraw")->rollback();
            return $this->error('', $e->getMessage());
        }

    }

    /**
     * 获取店铺提现
     * @param array $condition
     * @param string $field
     */
    public function getShopWithdrawInfo($condition = [], $field = '*')
    {
        $info = model('hotel_withdraw')->getInfo($condition, $field);
        return $this->success($info);
    }
    /**
     * 获取店铺转账列表
     * @param array $condition
     * @param string $field
     * @param string $order
     * @param string $limit
     */
    public function getShopWithdrawList($condition = [], $field = '*', $order = '', $limit = null)
    {

        $list = model('hotel_withdraw')->getList($condition, $field, $order, '', '', '', $limit);
        return $this->success($list);
    }

    /**
     * 获取店铺转账分页列表
     * @param array $condition
     * @param number $page
     * @param string $page_size
     * @param string $order
     * @param string $field
     */
    public function getShopWithdrawPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = '', $field = '*')
    {

        $list = model('hotel_withdraw')->pageList($condition, $field, $order, $page, $page_size);
        return $this->success($list);
    }


    /**
     * 设置商家转账设置
     */
    public function setHotelWithdrawConfig($data)
    {
        $config = new Config();
        $res = $config->setConfig($data, '酒店转账设置', 1, [['site_id', '=',  0], ['app_module', '=', 'admin'], ['config_key', '=', 'HOTEL_WITHDRAW']]);

        $cron = new Cron();
        switch($data['period_type'])
        {
            case 1://天

                $date = strtotime(date('Y-m-d 00:00:00'));
                $execute_time = strtotime('+1day',$date);
                break;
            case 2://周

                $execute_time = Carbon::parse('next monday')->timestamp;
                break;
            case 3://月

                $execute_time = Carbon::now()->addMonth()->firstOfMonth()->timestamp;
                break;
        }

        $cron->deleteCron([ [ 'event', '=', 'HotelSettlement' ] ]);
        $cron->addCron('2','1','酒店周期结算','HotelSettlement',$execute_time,'0',$data['period_type']);

        return $res;
    }

    /**
     * 获取商家转账设置
     */
    public function getHotelWithdrawConfig()
    {
        $config = new Config();
        $res = $config->getConfig([['site_id', '=',  0], ['app_module', '=', 'admin'], ['config_key', '=', 'HOTEL_WITHDRAW']]);
        if(empty($res['data']['value']))
        {
            //默认数据管理
            $res['data']['value'] = [
                'is_period_settlement' => 1,  //是否账期转账
                'period_type' => 3,           //转账周期类型1.天  2. 周  3. 月
                'min_withdraw' => 0,          //最低提现金额，对手动申请提现有效
                'max_withdraw' => 0,          //最高提现金额 , 对手动申请提现有效
                'withdraw_rate' => 0,          //提现或者转账手续费，对整体有效
            ];
        }
        return $res;
    }

    /**************************************************************店铺提现转账结束**********************************************************/

    /**************************************************************店铺提现转账周期结算**********************************************************/
    /**
     * 店铺周期结算
     */
    public function shopWithdrawPeriodCalc()
    {
        //查询设置结算周期
        $config = $this->getHotelWithdrawConfig();
        if($config['data']['value']['is_period_settlement'] != 1)
        {
            return $this->error();
        }
        switch ($config['data']['value']['period_type'])
        {
            case 3:
                $period_name = date('Y-m-d')."月结";
                break;
            case 2:
                $period_name = date('Y-m-d')."周结";
                break;
            case 1:
                $period_name = date('Y-m-d')."日结";
                break;
        }
        model("hotel_withdraw_period")->startTrans();
        try{
            $period_data = [
                'remark' => $period_name,
                'end_time' => time(),
                'period_type' => $config['data']['value']['period_type']
            ];
            $period_id = model("hotel_withdraw_period")->add($period_data);

            $field = 'hotel_id,hotel_name,account,account_withdraw,bank_type,bank_number,id_card_name,telphone';


            $shop_list = model("hotel")->getList([], $field, '');
            $cache = 1111;
            $money = 0;
            $shop_count = 0;
            foreach ($shop_list as $k => $v)
            {

                $data = [
                    'withdraw_no' => date('YmdHi').$cache,
                    'hotel_id' => $v['hotel_id'],
                    'hotel_name' => $v['hotel_name'],
                    'name' => $v['id_card_name']  == null ? '' : $v['id_card_name'],
                    'mobile' => $v['telphone'] == null ? '' : $v['telphone'],
                    'bank_type' => $v['bank_type'] == null ? 0 : $v['bank_type'],
                    //'settlement_bank_account_name' => $v['settlement_bank_account_name'] == null ? '' : $v['settlement_bank_account_name'],
                    'settlement_bank_account_number' => $v['bank_number'] == null ? '' : $v['bank_number'],
                    //'settlement_bank_name' => $v['settlement_bank_name'] == null ? '' : $v['settlement_bank_name'],
                    //'settlement_bank_address' => $v['settlement_bank_address'] == null ? '' : $v['settlement_bank_address'],
                    'money' => $v['account'] == null ? '' : $v['account'],
                    'apply_time' => time(),
                    'status' => 1,
                    'is_period' => 1,
                    'period_id' => $period_id,
                    'period_name' => date('Y-m-d')."结算"
                ];
                $cache += 1;
                $shop_count++;
                $money += $v['account'];
                $this->addShopWithdraw($data);
            }
            //添加周期
            model("hotel_withdraw_period")->update(['money' => $money, 'shop_num' => $shop_count], [['period_id', '=', $period_id]]);
            model("hotel_withdraw_period")->commit();
            return $this->success();
        }catch(\Exception $e)
        {
            model("hotel_withdraw_period")->rollback();
            return $this->success('', $e->getMessage());
        }

    }
    /**
     * 获取店铺转账周期结算分页列表
     * @param array $condition
     * @param number $page
     * @param string $page_size
     * @param string $order
     * @param string $field
     */
    public function getShopWithdrawPeriodPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = '', $field = '*')
    {

        $list = model('hotel_withdraw_period')->pageList($condition, $field, $order, $page, $page_size);
        return $this->success($list);
    }
}